﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;

using NetBay.Core.BusinessEntities;
using NetBay.Core.Silverlight.Log;

using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Enums;
using Rio.Framework.Pages.Manager;
using Rio.Framework.WCFService;

namespace Rio.Manager.Application
{
    public partial class MainPage : UserControl
    {
        #region Constructors

        public MainPage()
        {
            InitializeComponent();
            busyIndicator.BusyContent = Resx.GetLabel(ResxCommon.LOADING_PAGE);

            if (LoginManager.Instance.AuthenticationMethod != LoginDomainServiceEnums.AuthenticationMethod.SSO)
            {
                BusinessEntitiesDomainContext ds = new BusinessEntitiesDomainContext();
                var getCurrentUserQuery = ds.GetCurentUserQuery();
                ds.Load(getCurrentUserQuery,
                        result =>
                        {
                            if (!result.HasError && result.Entities != null && result.Entities.Count() > 0 && result.Entities.First().IsValid)
                            {
                                LoginManager.Instance.SetUser(result.Entities.First());
                                Initialization();
                            }
                            else
                            {
                                NavigationHelper.Instance.NavigateToLogin();
                            }
                        },
                        null);
            }
            else
            {
                string ntmlAccount = GlobalWebContext.RioAppSettings["UserAccount"];
                ntmlAccount = ntmlAccount.Substring(ntmlAccount.IndexOf(@"\") + 1,
                                                    ntmlAccount.Length - ntmlAccount.IndexOf(@"\") - 1);

                if (LoginManager.Instance.CurrentUser == null)
                    LoginManager.Instance.AuthenticatedUser +=
                        (sender, args) => Initialization();
                else
                    Initialization();

                LoginManager.Instance.LogUser(ntmlAccount, String.Empty);
            }
        }

        #endregion Constructors

        private void Initialization()
        {
            headMenu.LoadUser(ApplicationName.RioManager);
            busyIndicator.Visibility = Visibility.Collapsed;
        }
    }
}